<!-- 登录 -->
<template>
    <div class="flex items-center justify-center min-h-screen bg-gray-950">
        <div class="bg-white p-12 rounded-lg shadow-lg w-96">
            <div>
                <img src="../../assets/logolight.svg" class="w-48 h-auto mx-auto my-8" />
            </div>

            <el-form :model="form" :rules="rules" ref="loginForm" @submit.prevent="handleSubmit">
                <el-form-item prop="username">
                    <el-input v-model="form.username" placeholder="用户名" clearable></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="form.password" placeholder="密码" show-password></el-input>
                </el-form-item>
                <el-form-item>
                    <el-text class="text-gray-400 text-xs"> 未注册用户直接注册 </el-text>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit" class="w-full" round>
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { authLogin } from '@/api/userApi';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

const form = ref({
    username: 'krisli',
    password: 'krisli123',
});

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const loginForm = ref<InstanceType<typeof ElForm> | null>(null);
const callbackUrl = ref<string | null>(null);

onMounted(() => {
    // 获取回调链接
    callbackUrl.value = route.query.cb_url as string;
});

const handleSubmit = async () => {
    await loginForm.value?.validate();

    try {
        const { data } = await authLogin(form.value.username, form.value.password);
        // 设置token
        localStorage.setItem('token', data.token);
        // 登录成功
        router.push(callbackUrl.value || '/home');
    } catch (error) {
        ElMessage.error((error as any).message);
    }
};
</script>
